<template>
    <div>
    <!--合并订单对话框-->
    <el-dialog title="合并订单" :visible.sync="dialogOrderMergeVisible">
      <el-form :model="OrderMergeform">
         <el-form-item label="主订单" :label-width="formLabelWidth">
          <el-select v-model="OrderMergeform[0]" placeholder="请选择活动区域">
            <el-option :key="item.id" v-for="item in OrderMergeList" :value="item.id">{{item.id}}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="从订单" :label-width="formLabelWidth">
          <el-select v-model="OrderMergeform[1]" placeholder="请选择活动区域">
           <el-option :key= "item.id" v-for="item in OrderMergeList" :value="item.id">{{item.id}}</el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="shutOrderMerge()">取 消</el-button>
        <el-button type="primary" @click="submitOrderMerge()">确 定</el-button>
      </div>
    </el-dialog>
    <!--拆分订单对话框-->
      <el-dialog title="拆分订单" :visible.sync="dialogOrderSplitVisible">
        <el-form :model="orderSplitMap">
            <template>
                <el-form :inline="true" :model="orderSplitMap" class="demo-form-inline">
                    <el-form-item label="需要拆分订单">
                        <el-input v-model="orderSplitMap.orderId" placeholder="输入订单号"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="orderSplit">查询</el-button>
                    </el-form-item>
                </el-form>
                <el-table
                :data="orderSplittableData"
                style="width: 100%">
                    <el-table-column
                        prop="orderName"
                        label="商品名称"
                        width="180">
                    </el-table-column>
                    <el-table-column
                        label="单价/货号"
                        width="180">
                        <template slot-scope="scope">
                            单价：{{scope.row.price}}
                            货号：{{scope.row.sn}}
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="spec"
                        label="属性">
                    </el-table-column>
                     <el-table-column
                        prop="totalNum"
                        label="数量">
                    </el-table-column>
                     <el-table-column
                        prop="num"
                        label="库存">
                    </el-table-column>
                     <el-table-column
                        label="拆分数量">
                        <template slot-scope="scope">
                              <el-input
                            placeholder="请输入内容"
                            v-model="orderSplitNumMap[scope.$index]"
                            clearable>
                             </el-input>
                        </template>
                    </el-table-column>
                </el-table>
            </template>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeDialogSplit()">取 消</el-button>
          <el-button type="primary" @click="dialogSplit()">确 定</el-button>
        </div>
      </el-dialog>
    <!--关闭订单对话框-->
        <el-dialog title="关闭订单" :visible.sync="dialogShutDownVisible">
        <el-form :model="ShutDownform">
          <el-form-item label="操作备注" :label-width="formLabelWidth">
            <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入内容"
            v-model="ShutDownform.remaks">
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeDialogshutDowm()">取 消</el-button>
          <el-button type="primary" @click="dialogshutDowm()">确 定</el-button>
        </div>
        </el-dialog>
      <el-row :gutter="10">
        <el-col :span="24">
            <el-button type="primary"  @click="statusButto()">全部订单</el-button>
            <el-button type="primary" :key="item.oStatus" v-for="item in StatusButton" @click="statusButto(item.oStatus)">
            {{item.oStatus==0? "待付款":
            item.oStatus==1? "待发货":
            item.oStatus==2? "已发货":
            item.oStatus==3? "已完成":
            item.oStatus==4? "已关闭":
            ""
            }}({{item.cStatus}})</el-button>
        </el-col>
      </el-row>
    <el-row :gutter="20">
        <!--查询表单-->
        <el-form :inline="true" :model="searchMap" class="demo-form-inline">
            <el-form-item label="输入搜索">
                <el-input v-model="searchMap.id" placeholder="订单编号"></el-input>
            </el-form-item>
            <el-form-item label="收货人">
                <el-input v-model="searchMap.receiverContact" placeholder="收货人/手机号码"></el-input>
            </el-form-item>
            <el-form-item label="提交时间">
                <el-date-picker
                v-model="searchMap.createTime"
                align="right"
                type="date"
                placeholder="请选择时间"
                :picker-options="pickerOptions"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd">
                </el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit">查询</el-button>
            </el-form-item>
        </el-form>
    </el-row>
    <el-row :gutter="20">
      <!--数据表格-->
      <template class="tableTemplate">
        <el-button type="primary" @click="dialogorderSplit()">拆分订单</el-button>
        <el-button type="primary" @click="openOrderMerge()">合并订单</el-button>
        <el-button type="primary" @click="btnClick()">打印发货单</el-button>
        <el-button type="primary" @click="BulkShippingButton()">批量发货</el-button>
      <el-table
      :data="tableData"
      border
      style="width: 100%"
      @selection-change="changeFun">
      <el-table-column type="selection"  width="50"></el-table-column>
      <el-table-column
        label="订单编号"
        width="180" prop="id">
      </el-table-column>
      <el-table-column
        label="提交时间"
        width="180" prop="createTime" :formatter="dateFormat">
      </el-table-column>
      <el-table-column
        label="用户账号"
        width="180" prop="username">
      </el-table-column>
      <el-table-column
        label="订单金额"
        width="180" prop="totalMoney">
         <template slot-scope="scope">
            ￥{{scope.row.totalMoney}}
        </template>
      </el-table-column>
      <el-table-column
        label="支付方式"
        width="180" prop="payType">
        <template slot-scope="scope">
            {{scope.row.payType == '0'? '未支付':scope.row.payType == '1'? '支付宝':'货到付款'}}
        </template>
      </el-table-column>
       <el-table-column
        label="订单来源"
        width="180" prop="sourceType">
        <template slot-scope="scope">
            {{scope.row.sourceType == '1'? 'app订单':
            scope.row.sourceType == '2'? 'web订单':
            scope.row.sourceType == '3'? '微信公众号':
            scope.row.sourceType == '4'? '微信小程序':
            'H5手机页面'}}
        </template>
      </el-table-column>
       <el-table-column
        label="订单状态"
        width="180" prop="orderStatus">
         <template slot-scope="scope">
            {{scope.row.orderStatus == '0'? '待付款':
            scope.row.orderStatus == '1'? '待发货':
            scope.row.orderStatus == '2'? '已发货':
            scope.row.orderStatus == '3'? '已完成':
            '已关闭'}}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="orderDetails(scope.row.id)">查看订单</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="{{scope.row.orderStatus == '0'? shutDowm(scope.$index, scope.row):
            scope.row.orderStatus == '1'? orderShip(scope.row):
            scope.row.orderStatus == '2'? orderTrack(scope.$index, scope.row):
            scope.row.orderStatus == '3'? orderTrack(scope.$index, scope.row):
            handleDelete(scope.$index, scope.row)}}">
            {{scope.row.orderStatus == '0'? '关闭订单':
            scope.row.orderStatus == '1'? '订单发货':
            scope.row.orderStatus == '2'? '订单跟踪':
            scope.row.orderStatus == '3'? '订单跟踪':
            '删除订单'}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="pageSizeList"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    </template>
    </el-row>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 显示数据
      tableData: [],
      // 当前页数
      currentPage: 1,
      // 页大小
      pageSize: 10,
      // 当前页显示多少数据
      pageSizeList: [10, 20, 50],
      // 总记录数
      total: 0,
      // 查询表单对象
      searchMap: {},
      // 对话框状态
      dialogFormVisible: false,
      // 对话框表单提交的数据
      form: {},
      // 对话框大小
      formLabelWidth: '120px',
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [{
          text: '今天',
          onClick (picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      dialogShutDownVisible: false, // 关闭订单对话框状态
      ShutDownform: {}, // 关闭订单框提交表单,
      orderSpliOrderIdtMap: [], // 拆分订单查询出订单号数据
      orderSplitMap: {},
      orderSplitNumMap: [],
      orderSplittableData: [], // 拆分订单表格数据
      dialogOrderSplitVisible: false, // 拆分订单对话框
      orderSplitList: [],
      dialogOrderMergeVisible: false, // 合并订单
      OrderMergeList: {}, // 合并订单保存所有订单数据
      OrderMergeform: [], // 合并订单 提交数组
      StatusButton: [], // 所有订单状态按钮的值
      bulkShippingAay: [],
      one: 0
    }
  },
  methods: {
    // 删除
    handleDelete (index, row) {
      const id = row.id
      this.$confirm('此操作将永久删除文件，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`/orders/order/delete/${id}`)
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '删除成功！'
          })
          this.getfindAll()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 获取品牌信息列表
    async getfindAll () {
      // 发送请求查询数据并返回
      const { data: res } = await this.$http.post(`/orders/order/findPage/${this.currentPage}/${this.pageSize}`, this.searchMap)
      const { data: status } = await this.$http.get('/orders/order/findStatus')
      this.StatusButton = status
      this.tableData = res.data.rows
      this.total = res.data.total
    },
    // 查询按钮
    onSubmit () {
      this.getfindAll()
    },
    // 页大小改变
    async handleSizeChange (val) {
      this.pageSize = val
      this.getfindAll()
    },
    // 页码改变
    async handleCurrentChange (val) {
      this.currentPage = val
      this.getfindAll()
    },
    // 添加或编辑窗口打开
    async addOrUpdateForm (id) {
      if (id != null) {
        const { data: res } = await this.$http.get(`/orders/order/findById/${id}`)
        this.form = res.data
      }
      // this.form.id = id
      this.imageUrl = this.form.image
      this.dialogFormVisible = true
      console.log(this.form.id == null ? 'insert' : 'update')
    },
    // 添加或修改
    async save () {
      this.form.image = this.imageUrl
      console.log(this.form.id == null ? 'insert' : 'update')
      const { data: res } = await this.$http.post(`/orders /order/${this.form.id == null ? 'insert' : 'update'}`, this.form)
      console.log(res)
      this.getfindAll()
      this.dialogFormVisible = false
    },
    // 关闭窗口
    closeDialog () {
      // ..
      this.form = {}
      this.dialogFormVisible = false
    },
    // 关闭订单
    shutDowm (index, row) {
      this.ShutDownform.orderId = row.id
      console.log(row)
      this.dialogShutDownVisible = true
    },
    closeDialogshutDowm () {
      // ..
      this.ShutDownform = {}
      this.dialogShutDownVisible = false
    },
    async dialogshutDowm () {
      console.log(this.ShutDownform)
      const { data: res } = await this.$http.post(`/orders/order/updateLog/${this.ShutDownform.orderId}`, this.ShutDownform)
      if (res.code === 200) {
        this.$message({
          type: 'success',
          message: '关闭成功'
        })
        this.dialogShutDownVisible = false
        this.getfindAll()
      }
    },
    // 订单发货
    orderShip (row) {
      this.bulkShippingAay.push(row)
      this.$router.push({ name: 'BulkShipping', query: { order: this.bulkShippingAay } })
    },
    // 订单跟踪
    orderTrack (index, row) {
      console.log(row.id)
      this.$router.push({ name: 'OrderTrack', query: { orderId: row.id } })
    },
    // 订单详情
    orderDetails (id) {
      this.$router.push({ path: '/OrderDetails', query: { orderId: id } })
    },
    // 拆分订单查询当前订单数据
    dialogorderSplit () {
      this.dialogOrderSplitVisible = true
    },
    closeDialogSplit () {
      // ..
      this.orderSplitMap = {}
      this.orderSplittableData = []
      this.dialogOrderSplitVisible = false
    },
    async orderSplit () {
      const { data: order } = await this.$http.get(`/orders/order/findById/${this.orderSplitMap.orderId}`)
      const { data: res } = await this.$http.get(`/orders/order/orderSplit/${this.orderSplitMap.orderId}`)
      if (order.data.orderStatus < 2) {
          this.orderSplittableData = res.data
      } else {
          this.$message({
          type: 'success',
          message: '请输入待付款或待发货订单'
        })
      }
      console.log(res)
    },
    async dialogSplit () {
      // this.orderSplitMap.orderId = this.orderSplitMap.orderId
      // this.orderSplitList.push((this.orderSplitNumMap)
      // this.orderSplitList.push((this.orderSplitNumMap)
      console.log(this.orderSplitNumMap)
      for (let i = 0; i < this.orderSplitNumMap.length; i++) {
        const orderMap = {}
        orderMap.orderId = this.orderSplitMap.orderId
        orderMap.num = this.orderSplitNumMap[i]
        this.orderSplitList.push(orderMap)
      }
      const { data: res } = await this.$http.post('/orders/order/orderSplit', this.orderSplitList)
      if (res.code === 200) {
        this.$message({
          type: 'success',
          message: '拆分成功！'
        })
        this.orderSplitMap = {}
        this.orderSplittableData = []
        this.orderSplitList = []
        this.dialogOrderSplitVisible = false
        this.getfindAll()
      }
    },
    // 打开合并订单
    async openOrderMerge () {
      const { data: res } = await this.$http.get('/orders/order/findAll')
      this.OrderMergeList = res.data
      this.dialogOrderMergeVisible = true
      console.log(this.OrderMergeList)
    },
    // 提交合并订单请求
    async submitOrderMerge () {
      this.one = 0
      for (let i = 0; i < this.OrderMergeform.length; i++) {
        const { data: order1 } = await this.$http.get(`/orders/order/findById/${this.OrderMergeform[i]}`)
        for (let j = 0; j < this.OrderMergeform.length; j++) {
          const { data: order2 } = await this.$http.get(`/orders/order/findById/${this.OrderMergeform[j]}`)
          console.log(order1)
          console.log(order2)
          console.log(order1.data.orderStatus)
          console.log(order2.data.orderStatus)
          if (order1.data.orderStatus === order2.data.orderStatus && (order1.data.orderStatus < 2 && order2.data.orderStatus < 2)) {
            this.one = this.one + 1
            if (this.one === this.OrderMergeform.length) {
              const { data: res } = await this.$http.post(`/orders/order/orderMerge?ids=${this.OrderMergeform}`)
              if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '合并成功！'
              })
              this.OrderMergeList = {}
              this.OrderMergeform = []
              this.dialogOrderMergeVisible = false
              this.getfindAll()
              }
            }
          } else {
             this.$message({
              type: 'warning',
              message: '请选择同样状态或未发货之前的订单'
            })
            break
          }
        }
      }
    },
    // 关闭合共订单
    shutOrderMerge () {
      this.OrderMergeList = {}
      this.OrderMergeform = []
      this.dialogOrderMergeVisible = false
    },
    // 打印发货单
    btnClick () {
      const vm = this
      vm.$router.push('/Invoice')
    },
    // 订单状态按钮查询
    async statusButto (one) {
      this.searchMap.orderStatus = one
      const { data: res } = await this.$http.post(`/orders/order/findPage/${this.currentPage}/${this.pageSize}`, this.searchMap)
      const { data: status } = await this.$http.get('/orders/order/findStatus')
      this.StatusButton = status
      this.tableData = res.data.rows
      this.total = res.data.total
    },
    // 批量发货跳转
    BulkShippingButton () {
      for (let i = 0; i < this.bulkShippingAay.length; i++) {
        if (!(this.bulkShippingAay[i].orderStatus === '1')) {
          this.$message({
            type: 'info',
            message: '请选择待发货订单'
          })
          break
        } else {
          this.$router.push({ name: 'BulkShipping', query: { order: this.bulkShippingAay } })
        }
      }
    },
    selectAll: function () {
      console.log(this.bulkShippingAay)
    },
    changeFun (val) {
      this.bulkShippingAay = val
      console.log(this.bulkShippingAay)
    },
     dateFormat (row, column, cellValue, index) {
                   const daterc = row[column.property]
                   if (daterc != null) {
                       const dateMat = new Date(parseInt(daterc.replace("/Date(", "").replace(")/", ""), 10));
                      const year = dateMat.getFullYear();
                    const month = dateMat.getMonth() + 1;
                    const day = dateMat.getDate();
                    var hh = dateMat.getHours();
                    if (hh < 10) {
                      hh = '0' + hh
                    }
                    var mm = dateMat.getMinutes();
                    if (mm < 10) {
                      mm = '0' + mm
                    }
                    var ss = dateMat.getSeconds();
                    if (ss < 10) {
                      ss = '0' + ss
                    }
                    const timeFormat = year + "/" + month + "/" + day + " " + hh + ":" + mm + ":" + ss;
                    return timeFormat;
                   }
            }
  },
  // 钩子函数
  async created () {
    this.getfindAll()
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .el-row {
    margin-bottom: 20px;
    &:last-child {
        margin-bottom: 0;
    }
  }
  .el-col {
    border-radius: 4px;
  }
  .bg-purple-dark {
    background: #99a9bf;
  }
  .bg-purple {
    background: #d3dce6;
  }
  .bg-purple-light {
    background: #e5e9f2;
  }
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }
  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }
</style>
